package com.pimee.web.monitor;

import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.pimee.common.constants.Constants.OnlineStatus;
import com.pimee.common.util.shiro.ShiroUtils;
import com.pimee.model.SysUserOnline;
import com.pimee.service.admin.ISysUserOnlineService;
import com.pimee.support.shiro.session.OnlineSession;
import com.pimee.support.shiro.session.PmRedisSessionDAO;
import com.pimee.web.AbstractController;

import io.swagger.annotations.ApiOperation;

@Controller
@RequestMapping("admin/monitor/online")
public class MonitorOnlineController extends AbstractController {

	@Autowired
	private ISysUserOnlineService userOnlineService;
	@Autowired
	private PmRedisSessionDAO ubRedisSessionDAO;

	@ApiOperation("查询通知分页列表")
	@RequiresPermissions("system:notice:list")
	@ResponseBody
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	public Object pageList(@RequestParam Map<String, Object> params, ModelMap modelMap) {
		PageInfo<Map<String, Object>> pageList = userOnlineService.pageList(params);
		return setSuccessModelMap(modelMap, pageList);
	}

	@RequiresPermissions("monitor:online:forceLogout")
	@PostMapping("/forceLogout")
	@ResponseBody
	public Object forceLogout(String sessionId, ModelMap modelMap) {
		SysUserOnline online = userOnlineService.selectOnlineBySessionId(sessionId);
		if (sessionId.equals(ShiroUtils.getSessionId())) {
			return this.setSuccessModelMap(modelMap, "当前登陆用户无法强退");
		}
		if (online == null) {
			return this.setSuccessModelMap(modelMap, "用户已下线");
		}
		OnlineSession onlineSession = (OnlineSession) ubRedisSessionDAO.readSession(online.getSessionId());
		if (onlineSession == null) {
			
			
			return this.setSuccessModelMap(modelMap, "用户已下线");
		}
		onlineSession.setStatus(OnlineStatus.OFFLINE);
		ubRedisSessionDAO.update(onlineSession);
		online.setStatus(OnlineStatus.OFFLINE.getCode());
		userOnlineService.saveOnline(online);
		return this.setSuccessModelMap(modelMap);
	}
}
